package com.aiju.cash.util;

import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.widget.RemoteViews;

import com.aiju.cash.R;
import com.aiju.utils.L;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author: 佐为
 * @date: 2017-01-09 09:27
 * @version: V1.0
 * @Description: 描述
 */
public class NotificationDown {

    private File fileInstall;
    private Context context;
    private Notification notify;
    private NotificationManager manager;

    /**
     * 更新通知栏
     */
    private Handler completeHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {// 更新通知栏
            if (msg.what < 100) {
                notify.contentView.setTextViewText(R.id.notify_updata_values_tv, msg.what + "%");
                notify.contentView.setProgressBar(R.id.notify_updata_progress, 100, msg.what, false);
                manager.notify(100, notify);
            } else {
                notify.contentView.setTextViewText(R.id.notify_updata_values_tv, "下载完成");
                notify.contentView.setProgressBar(R.id.notify_updata_progress, 100, msg.what, false);// 清除通知栏
                manager.cancel(100);
                installApk(fileInstall);
            }
        }
    };

    public NotificationDown(Context context) {
        this.context = context;
        this.manager = (NotificationManager) context.getSystemService((context.NOTIFICATION_SERVICE));
        this.notify = new Notification();
    }

    /**
     * 下载apk
     * @param apkUri
     */
    public void downLoadNewApk(String apkUri, String version) {
        notify.icon = R.mipmap.icon_launcher; // 通知栏显示所用到的布局文件
        notify.contentView = new RemoteViews(context.getPackageName(), R.layout.view_notify_item);
        manager.notify(100, notify);//建立下载的apk文件
        File appDir = new File(Environment.getExternalStorageDirectory(), "Boohee");//建立下载的apk文件
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = "aiju" + version + ".apk";
        fileInstall = new File(appDir, fileName);
        if (!fileInstall.exists()) {
            fileInstall.getParentFile().mkdirs();
            try {
                fileInstall.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        L.d(fileInstall.getAbsolutePath());
        downLoadSchedule(apkUri, completeHandler, context, fileInstall);
    }

    /**
     * 连接网络,下载一个文件,并传回进度
     * @param uri
     * @param handler
     * @param context
     * @param file
     */
    public static void downLoadSchedule(final String uri, final Handler handler, Context context, final File file) {
        if (!file.exists()) {
            handler.sendEmptyMessage(-1);
            L.e("文件不存在");
            return;
        }// 每次读取文件的长度
        final int perLength = 4096;
        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    URL url = new URL(uri);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setDoInput(true);
                    conn.connect();
                    InputStream in = conn.getInputStream();// 2865412
                    long length = conn.getContentLength();// 每次读取1k
                    byte[] buffer = new byte[perLength];
                    int len = -1;
                    FileOutputStream out = new FileOutputStream(file);
                    int temp = 0;
                    while ((len = in.read(buffer)) != -1) {// 写入文件
                        out.write(buffer, 0, len);// 当前进度
                        int schedule = (int) ((file.length() * 100) / length);// 通知更新进度（10,7,4整除才通知，没必要每次都更新进度）
                        if (temp != schedule && (schedule % 10 == 0 || schedule % 4 == 0 || schedule % 7 == 0)) {// 保证同一个数据只发了一次
                            temp = schedule;
                            handler.sendEmptyMessage(schedule);
                        }
                    }
                    out.flush();
                    out.close();
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    /**
     * 安装apk
     * @param file
     */
    private void installApk(File file) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(android.content.Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        context.getApplicationContext().startActivity(intent);
    }
}
